package mblog.web.controller.front;

import javax.servlet.http.HttpServletRequest;

import mblog.web.controller.BaseController;
import mtons.modules.pojos.UserProfile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.service.UserService;
import com.faxsun.web.pojos.FSUserProfile;
import com.faxsun.web.security.authentication.LoginMessage;

/**
 * 
 * @author langhsu
 *
 */
@Controller
public class LoginController extends BaseController {
	private static final Logger LOG = LoggerFactory
			.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	
	@Autowired
	private IndexController indexController;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String view(HttpServletRequest request,ModelMap model) {
		model.addAttribute("redirectUrl", request.getParameter("refer"));
		model.addAttribute("isLoginProcess", true);
		return indexController.root(request,1,model);
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public LoginMessage login(String username, String password, ModelMap model) {
		LoginMessage ret = new LoginMessage();
		try {
			UserProfile profile = userService.login(username, password);
			if (profile != null) {
				// record the login status
				putProfile(profile);
				// return "redirect:" + Views.HOME;
				// FIXME:定义返回内容
				// return "success";
				ret.retCode = 0;
				ret.user = (FSUserProfile) profile;
			} else {
				model.put("message", "用户名或密码错误");
				ret.message = "用户名或密码错误";
				ret.retCode = -2;
			}
		} catch (Exception e) {
			LOG.error("", e);
			ret.setRetCode(-3);
			ret.message = "服务器或网络故障，请稍后重试！";
		}

		return ret;
	}

}
